import React, { Component, Suspense } from 'react';
import { connect } from 'dva';
import GridContent from '@/components/PageHeaderWrapper/GridContent';
import PageLoading from '@/components/PageLoading';
import { Button, message, Form, Col, Select  } from 'antd';
import UserSession from '@/UserSession';
import { knowledgeDialogNodeInfo, knowledgeDialogAllDict } from "@/services/dialog";
const Item = React.lazy(() => import('./item'));
const { Option } = Select;

@connect(({ collectSlot, loading }) => ({
  collectSlot,
  loading: loading.effects['collectSlot/fetchSlot'],
}))
class Set extends Component {
  constructor(props) {
    super(props);
    this.state = {
      dialogSlots: [],
      nodeId: props.nodeId,
      stage: props.stage,
      dialogId: props.dialogId,// 多轮对话id
      setting:{
        mapping:[],
        uniqueSlot:"",
        apiId:"",
        resultTitle:{
          multiResultTitle:"",
          singleResultTitle:""
        },
        noResultTitle:"",
        noResultAction:"",
        resultTemplate:"",
        field:"",
        filter:"",
        noResFilter:""
      },
      apiList:[],
      fieldList:[],
      apiObj:{
        requestFields:[],
        responseFields:[]
      }
    }
  }

  componentDidMount() {
    this.fetchSlot();
    this.loadActionApis();
  }

  fetchSlot=async()=>{
    const { dispatch } = this.props;
    const { dialogId,nodeId,stage} = this.state;
    let {setting,dialogSlots} = this.state;
    if (UserSession.isSystemKnowledge()) { 
			let res = await knowledgeDialogNodeInfo({
        dialogId,
				nodeId,
				nodeType: stage,
				field: "",
      });
      // if(res.code === 0 && res.code != undefined){
      //   return false;
      // }
      setting = res.dialogStage.settings;
      dialogSlots = res.dialogSlots;
      let isEmptySetting = Object.keys(setting);
      if (!setting || isEmptySetting.length == 0) {
        setting = {
          mapping: [],
          uniqueSlot: "",
          apiId: "",
          resultTitle: {
            multiResultTitle: "",
            singleResultTitle: "",
          },
          noResultTitle: "",
          noResultAction: "",
          resultTemplate: "",
          field: "",
          filter: "",
          noResFilter: "",
        };
      }
      if (!dialogSlots) {
        dialogSlots = [];
      }
      if (setting.apiId) {
        this.getApiInfo(setting.apiId, true);
      }
      this.setState({
        dialogSlots,
        setting,
      });
    } else {
      dispatch({
        type: "collectSlot/fetchSlot",
        payload: {
          dialogId,
          nodeId,
          stage,
          field: "",
          urlPrefix: UserSession.isSystemKnowledge() ? 1 : null,
        },
        callback: (res) => {
          // if(res.code === 0 && res.code != undefined){
          //   return false;
          // }
          setting = res.dialogStage.settings;
          dialogSlots = res.dialogSlots;
          let isEmptySetting = Object.keys(setting);
          if (!setting || isEmptySetting.length == 0) {
            setting = {
              mapping: [],
              uniqueSlot: "",
              apiId: "",
              resultTitle: {
                multiResultTitle: "",
                singleResultTitle: "",
              },
              noResultTitle: "",
              noResultAction: "",
              resultTemplate: "",
              field: "",
              filter: "",
              noResFilter: "",
            };
          }
          if (!dialogSlots) {
            dialogSlots = [];
          }
          if (setting.apiId) {
            this.getApiInfo(setting.apiId, true);
          }
          this.setState({
            dialogSlots,
            setting,
          });
        },
      });
    }
    
  };


  getAllDict = async () => {
    const { dispatch } = this.props;
    const { dialogId} = this.state;
    if (UserSession.isSystemKnowledge()) {
			let res = await knowledgeDialogAllDict({ dialogId });
			if(res.code === 0 && res.code != undefined){
        return false;
      }
      this.setState({
        dicts:res
      })
		} else {
      dispatch({
        type: 'collectSlot/getAllDict',
        payload: {
          dialogId,
          urlPrefix: UserSession.isSystemKnowledge() ? 1 : null,
        },
        callback:(res)=>{
          if(res.code === 0 && res.code != undefined){
            return false;
          }
          this.setState({
            dicts:res
          })
        }
      });
    }
  };


  loadActionApis = () => {
    const { dispatch } = this.props;

    dispatch({
      type: 'dialogCommon/loadActionApis',
      payload: {
        page: 0,
        limit: 99999,
        urlPrefix: UserSession.isSystemKnowledge() ? 1 : null,
      },
      callback: (res) => {
        this.setState({
          apiList: res == null ? [] : res,
        });
      }
    });
  };

  getApiInfo= (id,isFirst)=>{
    const { dispatch } = this.props;
    dispatch({
			type: "dialogCommon/loadActionApi",
			payload: {
				apiId: id,
				urlPrefix: UserSession.isSystemKnowledge() ? 1 : null,
			},
			callback: (res) => {
				if (res.code === 0 && res.code != undefined) {
					return false;
				}
				if (isFirst) {
					this.setState({
						fieldList: res.responseFields.concat(res.requestFields),
						apiObj: res,
					});
				} else {
					this.setState({
						fieldList: res.responseFields,
						apiObj: res,
					});
				}
			},
		});
  };

  fixData=(arr)=>{
    let {setting} = this.state;
    setting = arr;
    this.setState({
      setting
    })
  };

  fixFieldList = (type)=>{
    let {apiObj,fieldList} = this.state;
    if(type === 'request'){
      fieldList = apiObj.requestFields;
    }else{
      fieldList = apiObj.responseFields;
    }
    fieldList = apiObj[type+'Fields'];
    this.setState({
      fieldList
    })
  };

  saveSlotCheck=()=>{
    const { dispatch,closeDrawer } = this.props;
    const { dialogId,nodeId,setting,stage} = this.state;
    if(this.Setting.getEditContent() === ''){
      return message.error('展示模版不能为空')
    }
    setting.resultTemplate = this.Setting.getEditContent();
    dispatch({
      type: 'collectSlot/saveSlot',
      payload: {
        field:'setting',
        id:`${dialogId}-${nodeId}`,
        setting,
        stage
      },
      callback:(res)=>{
        // if(res.code && res.code !== undefined){
        //   return false;
        // }
        message.info(res.msg);
        closeDrawer();
      }
    });
  };

  render() {
    const {dialogSlots,setting,apiList,apiObj} = this.state;
    return (
      <GridContent>
        <Suspense fallback={<PageLoading />}>
          <Col>
            <Item
              data={setting}
              apiData={apiList}
              fields={apiObj}
              dialogs={dialogSlots}
              updata={(res)=>this.fixData(res)}
              getApiDetail={(id)=>this.getApiInfo(id)}
              updataField={(type)=>this.fixFieldList(type)}
              wrappedComponentRef={e => this.Setting = e}
            />
            <Button type="primary" htmlType='button' onClick={()=>this.saveSlotCheck()} style={{marginTop:20}} disabled={UserSession.isSystemKnowledge()}>保存</Button>
          </Col>
        </Suspense>
      </GridContent>
    );
  }
}

export default connect (({ user }) => ({
  currentUser: user.currentUser
}))(Form.create()(Set));
